// pages/custom/index.js
var app = getApp();
var core = app.requirejs('core');
var diypage = app.requirejs('biz/diypage');
var diyad = app.requirejs('biz/ad');
var $ = app.requirejs('jquery')
Page(app.sr.page({
  data: {
    imgUrls: [
      '',
      '',
      ''
    ],
    indicatorDotss: true,
    autoplays: true,
    intervals: 2000,
    durations: 500,
    circulars: true,
    adveradmin: true,
    clock: '',
    diypage: 'true',
    route: 'custom',

    /*广告结束*/
    shop: {},
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 500,
    circular: true,
    current: 0, //默认banner选择
    xxqactiveid: 0, // 选项卡默认

    pageid: 0,
    result: {},
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var $this = this;
    var res = wx.getSystemInfoSync()
    var pageid = $this.data.pageid;
    $this.setData({
      screenWidth: res.windowWidth
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    options = options || {};
    var $this = this;
    var pageid = options.pageid;
    if (pageid == undefined) {
      var pages = getCurrentPages(); //获取页面栈
      var url_arr = pages[pages.length - 1].route.split("/"); //当前页面路径/分割后的数组
      pageid = url_arr[url_arr.length - 1];
    }
    $this.setData({
      pageid: pageid,
      imgUrl: app.globalData.approot
    });
    // diypage.get(this, 'home');
    var scene = decodeURIComponent(options.scene);
    if (!options.id && scene) {
      var sceneObj = core.str2Obj(scene);
      options.id = sceneObj.id;
      if (sceneObj.mid) {
        options.mid = sceneObj.mid;
      }
    }
    setTimeout(function() {
      $this.setData({
        areas: app.getCache("cacheset").areas
      });
    }, 3000)
    app.url(options);

    diypage.get(this, "diy", {
      id: pageid
    }, function(res) {
      if ($this.data.diypages) {
        let page = $this.data.diypages


        wx.setNavigationBarTitle({
          title: page.basicOption.pageTitle
        });
        wx.setNavigationBarColor({
          frontColor: page.basicOption.tabColor == 'white' ? '#ffffff' : '#000000',
          backgroundColor: page.basicOption.tabBackColor,
        })
      }



      /*启动广告*/
      if ($this.data.startadv == undefined || $this.data.startadv == '') {
        return
      }
      if ($this.data.startadv.status == 0 || $this.data.startadv == '') {
        wx.getSetting({
          success: function(res) {
            var limits = res.authSetting['scope.userInfo'];
            if (limits) {
              //$this.get_nopayorder();
              return
            }
          }
        })
      }

      var params = $this.data.startadv.params;
      if (params.style == 'default') {
        var timer = params.autoclose;

        function count_down(that) {
          $this.setData({
            clock: timer
          });
          if (timer <= 0) {
            $this.setData({
              adveradmin: false
            });
            return;
          }
          setTimeout(function() {
            timer -= 1;
            count_down(that);
          }, 1000)
        }
        count_down($this);
      }

      if (params.showtype == 1) {
        var showtime = params.showtime;
        var countdown = showtime * 1000 * 60;
        var startadvtime = app.getCache('startadvtime');
        var nowtime = +new Date();
        var adveradmin = true;
        $this.setData({
          adveradmin: true
        })
        if (startadvtime) {
          if ((nowtime - startadvtime) < countdown) {
            adveradmin = false;
          }
        }
        $this.setData({
          adveradmin: adveradmin
        });
        if (adveradmin) {
          app.setCache('startadvtime', nowtime);
        }
      }
      var advstatus = $this.data.startadv.status;
    });
    $this.setData({
      cover: true,
      showvideo: false
    });
    /**启动广告 */
    diyad.get(this, function(res) {


    })
    wx.getSystemInfo({
      success: function(res) {
        var swiperheight = res.windowWidth / 1.7
        $this.setData({
          swiperheight: swiperheight
        })
      }
    });
  },

  imagesHeight: function(e) {
    var width = e.detail.width,
      height = e.detail.height,
      type = e.target.dataset.type,
      $this = this;
    var isdot = e.currentTarget.dataset.isdot

    wx.getSystemInfo({
      success: function(res) {
        if (isdot == "dot_inside") {
          $this.data.result[type] = Number(res.windowWidth / width * height);
        } else {
          $this.data.result[type] = Number(res.windowWidth / width * height) + 30;
        }
        if (!$this.data[type] || ($this.data[type] && result[type] < $this.data[type])) {
          $this.setData({
            result: $this.data.result
          });
        }
      }
    });
  },
  bindInput: function(e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  startplay: function(e) {
    var cover = e.target.dataset.cover;
    this.setData({
      cover: cover,
      showvideo: true
    });
    this.videoContext = wx.createVideoContext('Video');
    this.videoContext.play()
  },


  phone: function() {
    var phoneNumber = this.data.phonenumber + ''
    wx.makePhoneCall({
      phoneNumber: phoneNumber
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function(e) {
    // innerAudioContext.play();

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: this.data.diypages.page.title,
    }
  },

  // 顶部菜单切换
  tabtopmenu: function(e) {
    var $this = this,
      diypages = $this.data.diypages,
      list = diypages.items,
      id = e.currentTarget.dataset.id,
      dataurl = e.currentTarget.dataset.url,
      type = e.currentTarget.dataset.type,
      topmenu = $this.data.topmenu,
      topmenuindex = e.currentTarget.dataset.index;
    pageid = $this.data.pageid;
    $this.setData({
      topmenuindex: topmenuindex
    })
    if (dataurl == '' || dataurl == undefined) {
      return;
    }
    if (dataurl.indexOf('pages') == 1) {
      console.error('1230' + pageid)
      var index = dataurl.lastIndexOf("=");
      var pageid = dataurl.substring(index + 1, dataurl.length);
      core.get('diypage', {
        id: pageid
      }, function(result) {
        if (result.error == 0) {
          var arr = [];
          for (var i in result.diypage.items) {
            arr.push(result.diypage.items[i]); //属性
          }
          arr.unshift(topmenu);
          var obj = new Object();
          for (var x in arr) {
            obj[x] = arr[x];
            if (arr[x].id == 'topmenu') {
              arr[x].status = type
            }
          }
          result.diypage.items = obj;
          $this.setData({
            diypages: result.diypage,
            topmenuDataType: ''
          })
        }
      });
    } else {
      core.get('diypage/getInfo', {
        dataurl: dataurl
      }, function(ret) {
        console.error('dataurl' + dataurl)
        var topmenu = $this.data.topmenu;
        core.get('diypage', {
          type: pageid
        }, function(result) {
          var diypage = result.diypage;
          $.each(diypage.items, function(id, item) {
            if (item.id == 'topmenu') {
              item.status = type
              for (var i in item.data) {
                if (i == type) {
                  item.data[i]['data'] = ret.goods.list;
                  if (ret.goods.list.length <= 8) {
                    // console.log(ret.goods.list.length)
                    item.data[i]['showmore'] = true
                    // console.log(item.data[i])
                  }
                }
              }
            }
          });
          if (result.error == 0) {
            $this.setData({
              diypages: result.diypage,
              topmenuDataType: ret.type
            })
          }
        });
      });
    }
    $this.setData({
      diypages: diypages
    })
  },
  // 选项卡切换
  tabwidget: function(e) {
    console.error(e)
    var $this = this,
      diypages = $this.data.diypages,
      list = diypages.items,
      id = e.currentTarget.dataset.id,
      dataurl = e.currentTarget.dataset.url,
      type = e.currentTarget.dataset.type;

    if (dataurl == '' || dataurl == undefined) {
      return;
    }

    core.get('diypage/getInfo', {
      dataurl: dataurl
    }, function(ret) {
      for (var i in diypages.items) {
        if (i == id) {
          diypages.items[i].data[type].data = ret.goods.list;
          diypages.items[i].data[type].type = ret.type;
          diypages.items[i].type = ret.type;
          diypages.items[i].status = type;
          if (ret.goods.list.length <= 8) {
            diypages.items[i].data[type].showmore = true;
          }

          $this.setData({
            diypages: diypages
          })
        }
      }
    });
  },
  // 路由跳转
  navigateMf(e) {

    var url = e.currentTarget.dataset.url
    var re = /^[0-9]+.?[0-9]*/; //判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/;//判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/ 

    //跳转其他小程序
    if (url.appid) {

      wx.navigateToMiniProgram({
        appId: url.appid,
        path: url.urldata,
        extraData: {
          // foo: 'bar'
        }, //跳转到其他小程序传递的参数
        envVersion: 'develop',
        success(res) {
          wx.showModal({
            title: '跳转其他小程序',
            content: '',
            showCancel: false

          })
        },
        fail(res) {

          wx.showModal({
            title: '跳转失败',
            content: res.errMsg,
            showCancel: false
          })
        }
      })
    } else if (url.includes('?cate')) {
      let params = url.split('?')
      if (params[1].includes('cate')) {
        let cateid = params[1].split('=')[1]


        app.setCache("cateid", cateid)
      }
      wx.switchTab({
        url: url,
      })
    } else if (re.test(url)) {

      wx.makePhoneCall({
        phoneNumber: url //仅为示例，并非真实的电话号码
      })
    } else if (url == '/pages/index/index') {
      wx.switchTab({
        url: url,
      })
    } else {
      wx.navigateTo({
        url: url,
        fail: function() {
          wx.switchTab({
            url: url,
          })
        }
      })
    }
  },
  //banner 图点的样式
  changeBanner(e) {

    this.setData({
      current: e.detail.current
    })
  },
  // 广告关闭 
  closeAdver() {
    this.setData({
      showAdver: false
    })
  },
  // 选择选项卡
  changexuanxiangqia(e) {

    this.setData({
      xxqactiveid: e.target.dataset.id
    })
  },
}))